﻿using ConfigInfoWebPlatform.Model;
using Microsoft.Data.Sqlite;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace ConfigInfoWebPlatform.API.DBCommon
{
    /// <summary>
    /// 配置文件数据层
    /// </summary>
    public class DAL_ConfigFile
    {

        /// <summary>
        /// 配置文件数据层
        /// </summary>
        public DAL_ConfigFile()
        {
            freeSql = FreesqlFactory.GetFreeSql("configplatform");
        }
        private IFreeSql freeSql;
        
        /// <summary>
        /// 获取配置文件信息
        /// </summary>
        /// <param name="parentDir">父级目录</param>
        /// <returns>配置文件信息列表</returns>
        public List<ConfigFileInfoModel> GetConfigFiles(string parentDir)
        {
            List<ConfigFileInfoModel> re = new List<ConfigFileInfoModel>();
            var query = freeSql.Select<ConfigFiles>()
                             .WhereIf(!string.IsNullOrWhiteSpace(parentDir), x => x.ParentPath == parentDir)
                             .OrderBy(x => x.Name)
                             .ToList(x => new ConfigFileInfoModel()
                             {
                                 currentId = x.Currentid,
                                 parentId = x.Parentid,
                                 level = x.Level.Value,
                                 ctype = x.Ctype,
                                 name = x.Name,
                                 path = x.Path,
                                 parentPath = x.ParentPath,
                                 fileSize = x.Filesize,
                                 updateTime = x.Updatetime,
                                 createdTime = x.Createdtime,
                                 programId = x.Programid.Value,
                                 note = x.Note,
                                 status = x.Status
                             });

            re.AddRange(query);
            if(query!=null && query.Any())
            {
                foreach (var item in query)
                {
                    List<ConfigFileInfoModel> childRe = new List<ConfigFileInfoModel>();
                    if(string.IsNullOrEmpty(Path.GetExtension(item.path)))
                    {
                        childRe = GetConfigFiles(item.path);
                    }
                    else
                    {
                        continue;
                    }
                    if(childRe!=null && childRe.Count>0)
                    {
                        re.AddRange(childRe);
                    }
                }
            }
            return re;
        }

        /// <summary>
        /// 根据导航功能ID获取对应的配置文件集合
        /// </summary>
        /// <param name="programId">导航功能id</param>
        /// <returns></returns>
        public List<ConfigFileInfoModel> GetConfigFiles(long programId)
        {
            var query = freeSql.Select<ConfigFiles>()
                             .Where(x=>x.Programid==programId)
                             .ToList(x => new ConfigFileInfoModel()
                             {
                                 currentId = x.Currentid,
                                 parentId = x.Parentid,
                                 level = x.Level.Value,
                                 ctype = x.Ctype,
                                 name = x.Name,
                                 path = x.Path,
                                 parentPath = x.ParentPath,
                                 fileSize = x.Filesize,
                                 updateTime = x.Updatetime,
                                 createdTime = x.Createdtime,
                                 programId = x.Programid.Value,
                                 note = x.Note,
                                 status = x.Status
                             });
            return query;
        }

        /// <summary>
        /// 根据导航功能ID获取对应的配置文件集合
        /// </summary>
        /// <param name="programId">导航功能id</param>
        /// <returns></returns>
        public List<ConfigFileInfoModel> GetConfigFiles()
        {
            var query = freeSql.Select<ConfigFiles>()
                             .ToList(x => new ConfigFileInfoModel()
                             {
                                 currentId = x.Currentid,
                                 parentId = x.Parentid,
                                 level = x.Level.Value,
                                 ctype = x.Ctype,
                                 name = x.Name,
                                 path = x.Path,
                                 parentPath = x.ParentPath,
                                 fileSize = x.Filesize,
                                 updateTime = x.Updatetime,
                                 createdTime = x.Createdtime,
                                 programId = x.Programid.Value,
                                 note = x.Note,
                                 status = x.Status
                             });
            return query;
        }
        /// <summary>
        /// 获取当天添加的数据
        /// </summary>
        /// <returns></returns>
        public List<ConfigFileInfoModel> GetTodayConfigFiles() 
        {
            var query = freeSql.Select<ConfigFiles>()
                               .Where(x=>x.Createdtime.Contains(DateTime.Now.ToString("yyyy-MM-dd")))
                               .ToList(x => new ConfigFileInfoModel()
                               {
                                   currentId = x.Currentid,
                                   parentId = x.Parentid,
                                   level = x.Level.Value,
                                   ctype = x.Ctype,
                                   name = x.Name,
                                   path = x.Path,
                                   parentPath = x.ParentPath,
                                   fileSize = x.Filesize,
                                   updateTime = x.Updatetime,
                                   createdTime = x.Createdtime,
                                   programId = x.Programid.Value,
                                   note = x.Note,
                                   status = x.Status
                               });
            return query;
        }

        /// <summary>
        /// 获取配置文件信息
        /// </summary>
        /// <returns>配置文件信息列表</returns>
        public List<ConfigFileInfoModel> GetConfigFilesWithOutDir()
        {
            List<ConfigFileInfoModel> re = new List<ConfigFileInfoModel>();
            var query = freeSql.Select<ConfigFiles>()
                             .Where(x=>x.Ctype=="F")
                             .OrderBy(x => x.Name)
                             .ToList(x => new ConfigFileInfoModel()
                             {
                                 currentId = x.Currentid,
                                 parentId = x.Parentid,
                                 level = x.Level.Value,
                                 ctype = x.Ctype,
                                 name = x.Name,
                                 path = x.Path,
                                 parentPath = x.ParentPath,
                                 fileSize = x.Filesize,
                                 updateTime = x.Updatetime,
                                 createdTime = x.Createdtime,
                                 programId = x.Programid.Value,
                                 note = x.Note,
                                 status = x.Status
                             });

            re.AddRange(query);
            if (query != null && query.Any())
            {
                foreach (var item in query)
                {
                    List<ConfigFileInfoModel> childRe = new List<ConfigFileInfoModel>();
                    if (string.IsNullOrEmpty(Path.GetExtension(item.path)))
                    {
                        childRe = GetConfigFiles(item.path);
                    }
                    else
                    {
                        continue;
                    }
                    if (childRe != null && childRe.Count > 0)
                    {
                        re.AddRange(childRe);
                    }
                }
            }
            return re;
        }

        /// <summary>
        /// 判断文件是否存在
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public int ExistFile(string filePath)
        {
            var query = freeSql.Select<ConfigFiles>()
                             .Where(x => x.Path == filePath)
                             .Count();

            return Convert.ToInt32(query);
        }

        /// <summary>
        /// 获取某个文件在数据库存储的ID
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public string GetFileId(string filePath)
        {
            var query = freeSql.Select<ConfigFiles>()
                             .Where(x => x.Path == filePath)
                             .ToOne(x => x.Currentid);
            return query;
        }

        /// <summary>
        /// 获取某个文件在数据库存储的Level
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public int GetFileLevel(string filePath)
        {
            var query = freeSql.Select<ConfigFiles>()
                             .Where(x => x.Path == filePath)
                             .ToOne(x => x.Level);
            return query.HasValue?query.Value:0;
        }

        public bool InsertConfig(ConfigFiles config)
        {
            var result = freeSql.Insert<ConfigFiles>(config).ExecuteAffrows();
            return result > 0;
        }
        

        /// <summary>
        /// 添加配置文件信息
        /// </summary>
        /// <param name="configFileInfo">配置文件实体信息</param>
        /// <returns></returns>
        public int AddConfigFile(ConfigFileInfoModel configFileInfo)
        {
            ConfigFiles model = new ConfigFiles();
            model.Currentid = configFileInfo.currentId;
            model.Programid = configFileInfo.programId;
            model.Parentid = configFileInfo.parentId;
            model.Level = configFileInfo.level;
            model.Name = configFileInfo.name;
            model.Ctype = configFileInfo.ctype;
            model.Path = configFileInfo.path;
            model.ParentPath = configFileInfo.parentPath;
            model.Filesize = configFileInfo.fileSize;
            model.Createdtime = configFileInfo.createdTime;
            model.Updatetime = configFileInfo.updateTime;
            model.Status = configFileInfo.status;
            model.Note = configFileInfo.note;
            var result = freeSql.Insert<ConfigFiles>(model).ExecuteAffrows();
            return result;
        }

        /// <summary>
        /// 删除配置文件
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public int DeleteConfigFile(string filePath)
        {
            var result = freeSql.Delete<ConfigFiles>()
                              .Where(x => x.Path == filePath)
                              .ExecuteAffrows();

            return result;
        }

        /// <summary>
        /// 获取文件的状态
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public string GetFileStatus(string filePath)
        {
            var query = freeSql.Select<ConfigFiles>()
                             .Where(x => x.Path == filePath)
                             .ToOne(x => x.Status);
            return query;
        }

        /// <summary>
        /// 更新配置文件状态
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        public int UpdateStatus(string filePath, string status)
        {
            var result = freeSql.Update<ConfigFiles>()
                              .Set(x => x.Status == status)
                              .Where(x => x.Path == filePath)
                              .ExecuteAffrows();
            return result;
        }

        public int Tolower(string fileid, string name, string parentPath, string path)
        {
            var result = freeSql.Update<ConfigFiles>()
                              .Set(x => x.Name, name)
                              .Set(x => x.Path, path)
                              .Set(x => x.ParentPath, parentPath)
                              .Where(x => x.Currentid == fileid)
                              .ExecuteAffrows();

            return result;
        }

        /// <summary>
        /// 更新配置文件时间戳
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public int UpdateStamp(string filePath)
        {
            var result = freeSql.Update<ConfigFiles>()
                              .Set(x => x.Updatetime, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
                              .Where(x => x.Path == filePath)
                              .ExecuteAffrows();
            return result;
        }

        /// <summary>
        /// 更新配置文件备注
        /// </summary>
        public int UpdateNote(string filePath,string note)
        {
            var result = freeSql.Update<ConfigFiles>()
                              .Set(x => x.Note, note)
                              .Where(x => x.Path == filePath)
                              .ExecuteAffrows();
            return result;
        }


        public List<ConfigFileInfoModel> GetConfigFileList()
        {
            var query = freeSql.Select<ConfigFiles>()
                            .Where(x => x.Ctype.Equals("F"))
                            .OrderBy(x => x.Name)
                            .ToList(x => new ConfigFileInfoModel()
                            {
                                currentId = x.Currentid,
                                parentId = x.Parentid,
                                level = x.Level.HasValue?x.Level.Value:0,
                                ctype = x.Ctype,
                                name = x.Name,
                                path = x.Path,
                                parentPath = x.ParentPath,
                                fileSize = x.Filesize,
                                updateTime = x.Updatetime,
                                createdTime = x.Createdtime,
                                programId = x.Programid.HasValue?x.Programid.Value:Convert.ToInt64("0"),
                                note = x.Note,
                                status = x.Status
                            });
            return query;
        }


        public List<ConfigFiles> GetNavidNoneConfigs()
        {
            var query = freeSql.Select<ConfigFiles>()
                              .Where(x => x.Programid == 0)
                              .ToList();
            return query;
        }

        public ConfigFiles GetConfigFileByPath(string filePath)
        {
            var query = freeSql.Select<ConfigFiles>()
                             .Where(x => x.Path == filePath)
                             .ToOne();
            return query;
        }


        /// <summary>
        /// 修改配置文件菜单Id
        /// </summary>
        public bool UpdateConfigProgramid(string id,long programId)
        {
            var result = freeSql.Update<ConfigFiles>()
                              .Set(x => x.Programid, programId)
                              .Where(x => x.Currentid == id)
                              .ExecuteAffrows();
            return result > 0;
        }

        public bool DeleteConfigFileLike(string filePath)
        {
            var result = freeSql.Delete<ConfigFiles>()
                              .Where(x => x.Path.Contains(filePath))
                              .ExecuteAffrows();
            return result>0;
        }

        /// <summary>
        /// 修改配置文件ParentId
        /// </summary>
        public bool UpdateConfigParentId(string id, string parentId)
        {
            var result = freeSql.Update<ConfigFiles>()
                              .Set(x => x.Parentid, parentId)
                              .Where(x => x.Currentid == id)
                              .ExecuteAffrows();
            return result > 0;
        }

        /// <summary>
        /// 根据条件获取配置文件集合
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public List<ConfigFileInfoModel> GetConfigFilesByFilter(Expression<Func<ConfigFiles, bool>> where)
        {
            var select = freeSql.Select<ConfigFiles>()
                               .WhereIf(where != null, where)
                               .ToList(x => new ConfigFileInfoModel
                               {
                                   currentId = x.Currentid,
                                   parentId = x.Parentid,
                                   level = x.Level.HasValue ? x.Level.Value : 0,
                                   ctype = x.Ctype,
                                   name = x.Name,
                                   path = x.Path,
                                   parentPath = x.ParentPath,
                                   fileSize = x.Filesize,
                                   updateTime = x.Updatetime,
                                   createdTime = x.Createdtime,
                                   programId = x.Programid.HasValue ? x.Programid.Value : Convert.ToInt64("0"),
                                   note = x.Note,
                                   status = x.Status
                               });
            return select;
        }

        /// <summary>
        /// 根据条件获取单条配置文件信息
        /// </summary>
        public ConfigFiles GetSingleConfigByFilter(Expression<Func<ConfigFiles, bool>> where)
        {
            var query = freeSql.Select<ConfigFiles>()
                             .Where(where)
                             .ToOne();
            return query;
        }

        public void RefreshStatistics()
        {
            var desk = GetDeskStatistics();


        }

        public ConfigFileList GetDeskStatistics()
        {
            ConfigFileList configFileList = new ConfigFileList();
            int todayProcessFiles = 0;
            Expression<Func<ConfigFiles, bool>> where = null;

            #region 流程配置文件
            string processConfigPath = @"config/processconfig/analysisprocessconfig";
            where = where.And(x => x.Path.StartsWith(processConfigPath) && x.Ctype == "F");
            var processCfgFileInfos = GetConfigFilesByFilter(where);
            configFileList.processCfgFiles = processCfgFileInfos;
            if (processCfgFileInfos != null && processCfgFileInfos.Count > 0)
            {
                configFileList.processCfgFilesNum = processCfgFileInfos.Count;
                todayProcessFiles = processCfgFileInfos.Where(a => a.ctype == "F" && a.createdTime.Substring(0, 10) == DateTime.Now.ToString("yyyy-MM-dd")).ToList().Count();
            }
            else
            {
                configFileList.processCfgFilesNum = 0;
            }
            #endregion
            #region 模块配置文件
            string moduleConfigPath = @"config/moduleconfig";
            where = null;
            where = where.And(x => x.Path.StartsWith(moduleConfigPath) && x.Ctype == "F");
            var moduleCfgFileInfos = GetConfigFilesByFilter(where);
            configFileList.moduleCfgFiles = moduleCfgFileInfos;
            if (moduleCfgFileInfos != null && moduleCfgFileInfos.Count > 0)
            {
                configFileList.moduleCfgFileNum = moduleCfgFileInfos.Where(a => a.ctype == "F").ToList().Count;
            }
            else
            {
                configFileList.moduleCfgFileNum = 0;
            }
            #endregion

            #region 机器学习配置文件
            string MLConfigPath = @"config/mlconfig";
            where = null;
            where = where.And(x => x.Path.StartsWith(MLConfigPath) && x.Ctype == "F");
            var MLCfgFileInfos = GetConfigFilesByFilter(where);
            configFileList.MLCfgFiles = MLCfgFileInfos;
            if (MLCfgFileInfos != null && MLCfgFileInfos.Count > 0)
            {
                configFileList.MLCfigFileNum = MLCfgFileInfos.Count;
            }
            else
            {
                configFileList.MLCfigFileNum = 0;
            }
            #endregion
            #region 案件信息要素中心
            string caseElementConfigPath = @"config/elementnodescode";
            where = null;
            where = where.And(x => x.Path.StartsWith(caseElementConfigPath) && x.Ctype == "F");
            var caseElementCfgInfos = GetConfigFilesByFilter(where);
            configFileList.caseElementCfgFiles = caseElementCfgInfos;
            #endregion

            //获取所有文件；
            configFileList.TotalNum = GetConfigFilesWithOutDir().Count;

            //获取当天添加的数据
            configFileList.todayAddFiles = GetTodayConfigFiles().Count;
            return configFileList;
        }

        /// <summary>
        /// 修改配置文件备注
        /// </summary>
        public bool UpdateConfigFileNote(string id,string note)
        {
            var result = freeSql.Update<ConfigFiles>()
                              .Set(x => x.Note, note)
                              .Where(x => x.Currentid == id)
                              .ExecuteAffrows();
            return result > 0;
        }


    }
}
